import 'dart:io';

import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';

import '../common/flatPanel.dart';
import '../controller/traitSearchController.dart';
import '../entry.dart';
import '../utils/screw.dart';

class TraitSearchPage extends StatefulWidget {
  TraitSearchPage(
      {Key key, this.table = Entry.td_prefix, @required this.configName})
      : super(key: key);

  final String table;
  final String configName;

  @override
  _TraitSearchPageState createState() => _TraitSearchPageState();
}

class _TraitSearchPageState extends State<TraitSearchPage>
    with TraitSearchController {
  final _content = TextEditingController();

  @override
  void initState() {
    super.initState();
    mTable = widget.table;
    mLabels.add(pLabel);
  }

  @override
  void dispose() {
    super.dispose();
    _content.dispose();
    disposeAction();
  }

  @override
  void onConnectDb() async {
    await connectDbAction(context, widget.configName, onUpdateTopics);
  }

  @override
  void onUpdateTopics() async {
    await updateTopicsAction();
    setState(() {
      mViewState = ViewState.TopicView;
    });
  }

  @override
  void onUpdateLabels() async {
    await updateLabelsAction();
    setState(() {
      mLabel = mLabels.first;
      mViewState = ViewState.DetailView;
    });
  }

  Widget _genDropDownButton() {
    return DropdownButton<String>(
      isExpanded: true,
      hint: Text(pLabel, style: TextStyle(fontSize: 18)),
      value: mLabel,
      style: TextStyle(fontSize: 18, color: Colors.black),
      items: mLabels
          .map((e) => DropdownMenuItem<String>(
                value: e,
                child: Text(e),
              ))
          .toList(),
      onChanged: (v) {
        setState(() {
          mLabel = v;
        });
      },
    );
  }

  Widget _updateFloatingActionButton() {
    switch (mViewState) {
      case ViewState.Initial:
        return FloatingActionButton(
          child: FaIcon(FontAwesomeIcons.plug),
          onPressed: onConnectDb,
        );
      default:
        return genSpeedDialAction();
    }
  }

  void _onSearch() {
    if (_content.text.isEmpty) return;

    var content = _content.text.trim();
    if (mLabel.isEmpty || mLabel == pLabel) {
      Screw.baiduSearch(content);
      return;
    }

    if (content.startsWith('#')) {
      content = content.substring(1);
      if (!content.contains(','))
        Process.start(content, []);
      else {
        var items = content.split(',');
        var item = items.first;
        items.removeAt(0);
        Process.start(item, items);
      }
    } else {
      if (mCache.containsKey(mLabel)) {
        var prefix = mCache[mLabel];
        Screw.openUrl(prefix + content);
      }
    }
  }

  PopupMenuButton<String> _genPopupMenuButton() {
    return PopupMenuButton<String>(
      offset: Offset(0, 60),
      itemBuilder: (context) {
        return <PopupMenuEntry<String>>[
          PopupMenuItem<String>(
            value: 'updateTopics',
            child: ListTile(
              leading: Icon(Icons.read_more),
              title: Text('刷新类目'),
            ),
          ),
          PopupMenuItem<String>(
            value: 'updateCache',
            child: ListTile(
              leading: Icon(Icons.hourglass_bottom),
              title: Text('刷新缓存'),
            ),
          ),
        ];
      },
      onSelected: (value) {
        if (value == 'updateTopics')
          onUpdateTopics();
        else if (value == 'updateCache') updateCacheAction();
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(Entry.TraitSearch),
        actions: <Widget>[_genPopupMenuButton()],
      ),
      body: FlatPanel(
        margin: 32,
        padding: 32,
        child: Column(
          children: <Widget>[
            _genDropDownButton(),
            Row(
              children: <Widget>[
                Expanded(
                  flex: 1,
                  child: TextField(
                    controller: _content,
                    decoration: InputDecoration(
                      hintText: '关键词',
                      hintStyle: TextStyle(fontSize: 18),
                    ),
                    textInputAction: TextInputAction.search,
                  ),
                ),
                IconButton(
                  icon: Icon(Icons.search),
                  onPressed: _onSearch,
                ),
              ],
            ),
          ],
        ),
      ),
      floatingActionButton: _updateFloatingActionButton(),
    );
  }
}
